import React from 'react';
import LayoutContentWrapper from '@iso/components/utility/layoutWrapper';
import LayoutContent from '@iso/components/utility/layoutContent';
import axios from "@iso/http";
import Card from "@iso/containers/UIElements/Card/Card.styles";
import Button from '@iso/components/uielements/button';

import Modals from '@iso/components/Feedback/Modal';

import ModalStyle from '@iso/containers/Feedback/Modal/Modal.styles';
import WithDirection from '@iso/lib/helpers/rtl';

import {Fieldset, Form, Label} from "@iso/containers/FirestoreCRUD/Article/Article.styles";
import Input from '@iso/components/uielements/input';
import Qs from 'qs'

import {showErrorMessage,showSuccessMessage} from "@iso/containers/Feedback/Message/MessageUtils";

import {
    DateCell,
    ImageCell,
    LinkCell,
    TextCell,
} from '@iso/components/Tables/HelperCells';

import TableWrapper from "@iso/containers/Tables/AntTables/AntTables.styles";
import {Col, Row, Space, Tree} from "antd";
import PopconfirmWrapper from "@iso/containers/Feedback/Popconfirm/Popconfirm.styles";
import Popconfirms from '@iso/components/Feedback/Popconfirm';
import {DownOutlined} from "@ant-design/icons";
import { CheckboxGroup } from '@iso/components/uielements/checkbox';
import {InputGroup} from "@iso/components/uielements/input";
import PageHeader from '@iso/components/utility/pageHeader';
const isoModal = ModalStyle(Modals);
const Modal = WithDirection(isoModal);



const Popconfirm = (props) => (
    <PopconfirmWrapper>
        <Popconfirms {...props} />
    </PopconfirmWrapper>
);



export default class extends React.Component {


    constructor(props) {

        super(props);

        this.state={dataList:[],modalVisible:false,modalEditVisible:false,roleOptions: [],departmentTreeData:[],q_departmentName:'',q_name:'',q_realName:'',q_email:''};


    }


     renderCell = (object, type, key) => {
        const value = object[key];
        switch (type) {
            case 'ImageCell':
                return ImageCell(value);
            case 'DateCell':
                return DateCell(value);
            case 'LinkCell':
                return LinkCell(value);
            default:
                return TextCell(value);
        }
    };

    showAddModal=()=>{
        this.setState({modalVisible:true,name:'',realName:'',email:'',phone:'',password:'',confirmPassword:'',roleIds:[],departmentId:''})
    };

    handleCancel = () => {
        this.setState({modalVisible:false})
    };

    showEditModal=(item)=>{

        this.loadRoleForUser(item);

    };

    handleEditCancel = () => {
        this.setState({modalEditVisible:false})
    };

    onRecordChange = (event, key) => {
        let state={};
        state[key]=event.target.value;
        this.setState(state)
    };
    loadData=(page)=>{
        axios.post('api/base/user/findByPage', Qs.stringify({
            page: page-1,
            size: 10,
            name:this.state.q_name,
            realName:this.state.q_realName,
            organizationName:this.state.q_departmentName,
            email:this.state.q_email
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data

                let  dataList=data.data.content;

                for (let i=0;i<dataList.length;i++){
                    if(dataList[i].organization!=null){

                        dataList[i]["organizationId"] = dataList[i].organization.id

                    }else {
                        dataList[i]["organizationId"] = ""
                    }

                }

                let totalElements=data.data.totalElements;

                this.setState({dataList:dataList,totalElements:totalElements});
            })
            .catch(function (error) {
                console.log(error);
            });

    }
    loadRole=()=>{
        axios.post('api/base/role/findAll', Qs.stringify({
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data.data;

                let roleOptions=new Array();

                for(let i=0;i<data.length;i++){

                    let role=data[i];

                    roleOptions.push({label:role.name,value:role.id+""})
                }
                this.setState({roleOptions:roleOptions});
            })
            .catch(function (error) {
                console.log(error);
            });
    }


    loadDepartment=() =>{
        axios.post('api/base/organization/getTree', Qs.stringify({
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data

                let list=data.data

                this.setState({departmentTreeData:list});
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    loadRoleForUser=(item)=>{
        axios.post('api/base/role/findAllRoleForUser', Qs.stringify({
            userId:item.id
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data.data;

                let roleIds=new Array();

                for(let i=0;i<data.length;i++){

                    let role=data[i];

                    roleIds.push(role.id+"")
                }
                let state={
                    modalEditVisible:true,
                    id:item.id,
                    name:item.name,
                    realName:item.realName,
                    email:item.email,
                    phone:item.phone,
                    mobilePhone:item.mobilePhone,
                    company:item.company,
                    roleIds:roleIds,
                    password:'',
                    confirmPassword:'',
                    organizationId:item.organizationId,
                    departmentSelectedKeys:['organization_key_'+item.organizationId]

                };
                this.setState(state);
            })
            .catch(function (error) {
                console.log(error);
            });
    }


    add=() =>{
        let entity={
            name:this.state.name,
            realName:this.state.realName,
            phone:this.state.phone,
            email:this.state.email,
            mobilePhone:this.state.mobilePhone,
            company:this.state.company,
            roleIdList:this.state.roleIds,
            organizationId:this.state.organizationId,
            password:this.state.password,
            confirmPassword:this.state.confirmPassword
        };
        axios.post('api/base/user/add', entity,{headers: {'Content-Type': 'application/json'}})
            .then((response)=>{

                let  data=response.data;
                if (response.status==200){
                    if(data.status==1){
                        this.setState({modalVisible:false})
                        this.loadData();
                        showSuccessMessage(data.message)
                        return
                    }
                        showErrorMessage(data.message);

                    return
                }

                    for (let i=0;i<data.errors.length;i++){

                        showErrorMessage(data.errors[i].defaultMessage);
                    }


            })
            .catch(function (error) {
                console.log(error);
            });

    }
    update=() =>{
        let entity={
            id:this.state.id,
            realName:this.state.realName,
            phone:this.state.phone,
            email:this.state.email,
            mobilePhone:this.state.mobilePhone,
            company:this.state.company,
            roleIdList:this.state.roleIds,
            accountNonExpired:true,
            accountNonLocked:true,
            organizationId:this.state.organizationId,
            password:this.state.password,
            confirmPassword:this.state.confirmPassword
        };
        axios.post('api/base/user/update', entity,{headers: {'Content-Type': 'application/json'}})
            .then((response)=>{
                let  data=response.data;
                if (response.status==200){
                    if(data.status==1){
                        this.setState({modalEditVisible:false})
                        this.loadData();
                        showSuccessMessage(data.message)
                        return
                    }
                        showErrorMessage(data.message);
                    return

                }

                    for (let i=0;i<data.errors.length;i++){

                        showErrorMessage(data.errors[i].defaultMessage);
                    }


            })
            .catch(function (error) {
                console.log(error);
            });

    }


    deleteById=(id)=> {

        axios.post('api/base/user/deleteById', Qs.stringify({
            id:id
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.loadData(1);
                    showSuccessMessage(data.message)
                }else{
                    showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                console.log(error);
            });

    }


   componentDidMount() {
        this.loadDepartment()
        this.loadRole()
        this.loadData(1)
   }


    getColumns(){
        const columns = [ {
            title: 'ID',
            key: 'id',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'id'),
        },{
            title: '用户名',
            key: 'name',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'name'),
        },{
            title: '姓名',
            key: 'realName',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'realName'),
        },{
            title: '联系电话',
            key: 'phone',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'phone'),
        },{
            title: '电子邮箱',
            key: 'email',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'email'),
        },{
            title: '创建时间',
            key: 'createTime',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'createTime'),
        },{
            title: '操作',
            width: 100,
            render:(text,record) => (
            <Space size="middle">
                <Button
                    key={"edit"+record.id}
                    type="primary"
                    size="small"
                    onClick={()=>this.showEditModal(record)}
                >
                    编辑
                </Button>


                <Popconfirm
                    title="确定要执行删除操作吗？"
                    okText="是"
                    cancelText="否"
                    onConfirm={()=>this.deleteById(record.id)}

                >
                    <Button
                        key={"delete"+record.id}
                        type="danger"
                        size="small"

                    >
                        删除
                    </Button>
                </Popconfirm>
            </Space>
            )
        }];

        const sortColumns = [
            { ...columns[0], sorter: false },
            { ...columns[1], sorter: false },
            { ...columns[2], sorter: false },
            { ...columns[3], sorter: false },
            { ...columns[4], sorter: false },
            { ...columns[5], sorter: false },
            { ...columns[6], sorter: false }
        ];
        return sortColumns;
    }

    getPagination(){
      let pagination= {
        showSizeChanger: false,//设置每页显示数据条数
        showQuickJumper: false,
        showTotal: () => `共${this.state.totalElements}条`,
        pageSize: 10,
          //数据的总的条数
        total: this.state.totalElements,
          //点击当前页码
        onChange: (current) => this.loadData(current),
          //设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
        onShowSizeChange: (current, pageSize) => {
            console.log(pageSize);
            //this.onShowSizeChange(current, pageSize)
        }

     }
     return pagination;
    }



    roleCheckboxOnChange = checkedValues => {
        this.setState({"roleIds":checkedValues})
    };

    departmentOnSelect = (selectedKeys, info) => {
        this.setState({"organizationId":info.node.id})
        this.setState({departmentSelectedKeys:selectedKeys})
    }


    render() {
    return (
      <LayoutContentWrapper style={{ height: '100vh' }}>
          <PageHeader>
              用户管理
          </PageHeader>
        <LayoutContent style={{ height: '100vh',overflow:'scroll' }}>
            <Modal
                visible={this.state.modalVisible}
                title="添加"
                onCancel={this.handleCancel}
                footer={[
                    <Button key="back" size="small" onClick={this.handleCancel}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        size="small"
                        onClick={this.add}
                    >
                        确定
                    </Button>,
                ]}
            >
                <Form>
                        <Fieldset>
                            <Label>*用户名:</Label>
                            <Input
                                label="名称"
                                placeholder="请输入用户名"
                                value={this.state.name}
                                onChange={e => this.onRecordChange(e, 'name')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>*姓名:</Label>
                            <Input
                                label="名称"
                                placeholder="请输入用户真实姓名"
                                value={this.state.realName}
                                onChange={e => this.onRecordChange(e, 'realName')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>*电子邮箱:</Label>
                            <Input
                                label="电子邮箱"
                                placeholder="电子邮箱"
                                value={this.state.email}
                                onChange={e => this.onRecordChange(e, 'email')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>联系电话:</Label>
                            <Input
                                label="联系电话"
                                placeholder="联系电话"
                                value={this.state.phone}
                                onChange={e => this.onRecordChange(e, 'phone')}
                            />
                        </Fieldset>
                    <Fieldset>
                        <Label>手机号码:</Label>
                        <Input

                            placeholder="手机号码"
                            value={this.state.mobilePhone}
                            onChange={e => this.onRecordChange(e, 'mobilePhone')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>公司:</Label>
                        <Input

                            placeholder="公司"
                            value={this.state.company}
                            onChange={e => this.onRecordChange(e, 'company')}
                        />
                    </Fieldset>
                        <Fieldset>
                            <Label>*登录密码:</Label>
                            <Input
                                label="登录密码"
                                placeholder="登录密码"
                                type='password'
                                value={this.state.password}
                                onChange={e => this.onRecordChange(e, 'password')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>*确认密码:</Label>
                            <Input
                                label="确认密码"
                                placeholder="确认密码"
                                type='password'
                                value={this.state.confirmPassword}
                                onChange={e => this.onRecordChange(e, 'confirmPassword')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>所属机构:</Label>
                            <Tree
                                switcherIcon={<DownOutlined />}
                                onSelect={this.departmentOnSelect}
                                treeData={this.state.departmentTreeData}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>角色:</Label>
                            <CheckboxGroup
                                options={this.state.roleOptions}
                                onChange={this.roleCheckboxOnChange}
                            />
                        </Fieldset>

                    </Form>

            </Modal>


            <Modal
                visible={this.state.modalEditVisible}
                title="编辑"
                onCancel={this.handleEditCancel}
                footer={[
                    <Button key="back" size="small" onClick={this.handleEditCancel}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        size="small"
                        onClick={this.update}
                    >
                        确定
                    </Button>,
                ]}
            >
                <Form >
                    <Fieldset>
                        <Label>*用户名:</Label>
                        <Input
                            label="名称"
                            placeholder="请输入用户名"
                            value={this.state.name}
                            onChange={e => this.onRecordChange(e, 'name')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>*姓名:</Label>
                        <Input
                            label="名称"
                            placeholder="请输入用户真实姓名"
                            value={this.state.realName}
                            onChange={e => this.onRecordChange(e, 'realName')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>*电子邮箱:</Label>
                        <Input
                            label="电子邮箱"
                            placeholder="电子邮箱"
                            value={this.state.email}
                            onChange={e => this.onRecordChange(e, 'email')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>联系电话:</Label>
                        <Input
                            label="联系电话"
                            placeholder="联系电话"
                            value={this.state.phone}
                            onChange={e => this.onRecordChange(e, 'phone')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>手机号码:</Label>
                        <Input

                            placeholder="手机号码"
                            value={this.state.mobilePhone}
                            onChange={e => this.onRecordChange(e, 'mobilePhone')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>公司:</Label>
                        <Input

                            placeholder="公司"
                            value={this.state.company}
                            onChange={e => this.onRecordChange(e, 'company')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>*登录密码:</Label>
                        <Input
                            label="登录密码"
                            placeholder="登录密码"
                            type='password'
                            value={this.state.password}
                            onChange={e => this.onRecordChange(e, 'password')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>*确认密码:</Label>
                        <Input
                            label="确认密码"
                            placeholder="确认密码"
                            type='password'
                            value={this.state.confirmPassword}
                            onChange={e => this.onRecordChange(e, 'confirmPassword')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>所属机构:</Label>
                        <Tree
                            switcherIcon={<DownOutlined />}
                            onSelect={this.departmentOnSelect}
                            selectedKeys={this.state.departmentSelectedKeys}
                            treeData={this.state.departmentTreeData}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>角色:</Label>
                        <CheckboxGroup
                            options={this.state.roleOptions}
                            onChange={this.roleCheckboxOnChange}
                            value={this.state.roleIds}


                        />
                    </Fieldset>

                </Form>

            </Modal>

            <Card
                title='查询条件'
                style={{ width: '100%' }}
            >

                <InputGroup size="large" style={{ marginBottom: '15px' }}>
                    <Row gutter={8}>
                        <Col span={3}>
                            <Input placeholder='机构' onChange={e => this.onRecordChange(e, 'q_departmentName')} />
                        </Col>
                        <Col span={3}>
                            <Input  placeholder='用户名' onChange={e => this.onRecordChange(e, 'q_name')} />
                        </Col>
                        <Col span={3}>
                            <Input placeholder='姓名' onChange={e => this.onRecordChange(e, 'q_realName')} />
                        </Col>
                        <Col span={3}>
                            <Input placeholder='邮箱' onChange={e => this.onRecordChange(e, 'q_email')} />
                        </Col>
                        <Col span={3}>

                            <Button
                                key="button_query"
                                type="primary"
                                size="small"
                                onClick={()=>this.loadData(1)}
                            >
                                查询
                            </Button>
                        </Col>
                    </Row>
                </InputGroup>


            </Card>

            <Button
                key="submit"
                type="primary"
                size="small"
                onClick={()=>this.showAddModal()}
            >
                添加
            </Button>
            <Card
                title='查询结果'
                style={{ width: '100%' }}
            >

                <TableWrapper
                    columns={this.getColumns()}
                    dataSource={this.state.dataList}
                    className="isoSortingTable"
                    pagination={this.getPagination()}

                />

            </Card>



        </LayoutContent>
      </LayoutContentWrapper>
    );
  }
}
